package org.study.mongo.boot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import java.util.Optional;

/**
 * 去掉MongoDB数据库集合中的_class列
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年05月31日
 */
@Slf4j
@EnableMongoAuditing(auditorAwareRef = "auditorProvider")
@Configuration
public class MongoConfig {
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory mongoDatabaseFactory, MongoMappingContext mongoMappingContext) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
        DefaultMongoTypeMapper defaultMongoTypeMapper = new DefaultMongoTypeMapper(null);
        converter.setTypeMapper(defaultMongoTypeMapper);
        return converter;
    }

    @Bean
    public AuditorAware<String> auditorProvider() {
        AuditorAware<String> auditorAware = () -> {
            /*Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return Optional.empty();
            }
            // 返回当前用户名
            return Optional.of(((UserDetails) authentication.getPrincipal()).getUsername());*/
            return Optional.ofNullable("系统默认用户");
        };
        return auditorAware;
    }
}
